﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySQL.Db;

namespace Gollie.Ajax
{
	public class UserLogin : AjaxResult
	{
		public uint Id;
		public string UserName;
		public string FullName;
		public string QRAttr;
		public string WebToken;

		public uint VendorId = 0;
		public string VendorName;
		public string VendorStreet;
		public string VendorCity;
		public string VendorLogoAttr;

		public UserLogin() : base(null) { }

		public UserLogin(UserLoginArg arg)
			: base(arg)
		{

		}

		protected override void Init(AjaxArg ajaxArg)
		{
			UserLoginArg arg = (UserLoginArg)ajaxArg;

			try
			{
				UserInfo.ValidateUserName(arg.tokenUser);

				string wwHash = Hash.GetHash(arg.ww);
				
				ResultSet resultSet = Database.Queries.Login(arg.tokenUser, wwHash);

				if (resultSet.Count != 1)
				{
					this.ErrorCode = 4;
					throw new Exception("Gebruiker niet gevonden");
				}

				UserInfo userInfo = new UserInfo(resultSet);

				//user must be a regular customer, or a vendor-admin or -cashier
				if (userInfo.Role != Role.Customer && userInfo.Role != Role.Administrator && userInfo.Role != Role.Desk)
				{
					this.ErrorCode = 4;
					throw new Exception("Gebruiker niet gevonden");
				}

				Id = userInfo.Id;
				UserName = userInfo.Gebruikersnaam;
				FullName = userInfo.FullName;
				WebToken = userInfo.WebToken;

				if (userInfo.Role == Role.Customer)
					QRAttr = Helper.GetImageSrcAttribute(userInfo.QRCodePath);
				else
				{
					VendorName = userInfo.VendorInfo.BedrijfsNaam;
					VendorId = userInfo.VendorId;
					VendorCity = userInfo.VendorInfo.Plaats;
					VendorStreet = userInfo.VendorInfo.Straat;
					VendorLogoAttr = Helper.GetImageSrcAttribute(userInfo.VendorInfo.LogoSmallPath);
				}
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
			}
		}
	}
}